cphsoc_stata_legal_varnames <- function(vx,len=32,ptrn="",index.return=FALSE,stop_on_failure=FALSE)
{
  first_char <- substr(vx,1,1)
  # match against legal characters, returns NA for no match 
  # i.e. any non ascii char (and non-underscore) returns NA
  vx_tmp <- vx
  failure_idx <- integer()
  idx1 <- which(is.na(match(first_char,c(letters,LETTERS,'_'))))
  for(i in idx1)
  {
    if(is.na(x <- cphsoc_varname_first_char_ascii(vx_tmp[i],vx_tmp)))
    {
      if(stop_on_failure) 
      {
        stop(paste('Cannot convert ',vnm_tmp[i], ' to legal variable name'))
      }
      else
      {
        failure_idx <- c(failure_idx,i)
      }
    }
    else
    {
      vx_tmp[i] <- x
    }
  }
  
  idx2 <- which(nchar(vx_tmp)>len)
  for(i in idx2)
  {
    if(is.na(x <- cphsoc_varname_truncate(vx_tmp[i],vx_tmp,len=len)))
    {
      if(stop_on_failure) 
      {
        stop(paste('Cannot convert ',vnm_tmp[i], ' to legal variable name'))
      }
      else
      {
        failure_idx <- c(failure_idx,i)
      }
    }
    else
    {
      vx_tmp[i] <- x
    }
  }
  idx3 <- grep(ptrn,vx_tmp)
  for(i in idx3)
  {
    if(is.na(x <- cphsoc_varname_remove_illegal_chars(vx_tmp[i],vx_tmp,ptrn=ptrn)))
    {
      if(stop_on_failure) 
      {
        stop(paste('Cannot convert ',vnm_tmp[i], ' to legal variable name'))
      }
      else
      {
        failure_idx <- c(failure_idx,i)
      }
    }
    else
    {
      vx_tmp[i] <- x
    }
  }
  
  if(index.return)
  {
    return(list(x=vx_tmp,ix=unique(c(idx1,idx2,idx3))))
  }
  vx_tmp
}